<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-card">
        <div class="login-header">
          <h1 class="login-title">校园外卖派送系统</h1>
          <p class="login-subtitle">欢迎使用校园外卖派送系统</p>
        </div>

        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
                clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
                clearable
            />
          </el-form-item>

          <el-form-item prop="role">
            <el-select
                v-model="loginForm.role"
                placeholder="请选择角色"
                size="large"
                style="width: 100%"
                clearable
            >
              <el-option label="学生" value="STUDENT" />
              <el-option label="商家" value="MERCHANT" />
              <el-option label="配送员" value="DELIVERY" />
              <el-option label="管理员" value="ADMIN" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                size="large"
                style="width: 100%"
                :loading="loading"
                @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-footer">
          <span>还没有账号? </span>
          <router-link to="/register" class="register-link">立即注册</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  role: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const success = await userStore.login(loginForm)

    if (success) {
      ElMessage.success('登录成功')
      // 根据角色跳转到对应的首页
      const roleRoutes = {
        'STUDENT': '/student',
        'MERCHANT': '/merchant',
        'DELIVERY': '/delivery',
        'ADMIN': '/admin'
      }
      // 使用用户store中的实际角色，而不是表单中选择的角色
      const actualRole = userStore.userRole
      const targetRoute = roleRoutes[actualRole] || roleRoutes[loginForm.role] || '/student'
      
      console.log('登录成功，角色信息:', {
        formRole: loginForm.role,
        storeRole: actualRole,
        targetRoute: targetRoute
      })
      
      router.push(targetRoute)
    }
  } catch (error) {
    console.error('登录失败:', error)
    let errorMessage = '用户名或密码错误'

    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message && error.message !== '登录响应数据为空') {
      errorMessage = error.message
    }

    ElMessage({
      message: errorMessage,
      type: 'error',
      duration: 4000,
      showClose: true,
      center: true,
      offset: 80
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.login-background {
  width: 100%;
  max-width: 480px;
  min-width: 400px;
  padding: 0 20px;
  display: flex;
  justify-content: center;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 48px 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.login-form {
  margin-bottom: 24px;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-form .el-input__wrapper {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.login-form .el-input__wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
}

.login-form .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.login-form .el-button {
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-form .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.login-footer {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.register-link {
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.register-link:hover {
  color: #337ecc;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-background {
    max-width: 100%;
    min-width: auto;
  }

  .login-card {
    padding: 32px 24px;
  }

  .login-title {
    font-size: 24px;
  }
}

@media (min-width: 1200px) {
  .login-background {
    max-width: 520px;
  }

  .login-card {
    padding: 56px 48px;
  }

  .login-title {
    font-size: 32px;
  }
}

/* 动画效果 */
.login-card {
  animation: slideInUp 0.6s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 输入框图标样式 */
.el-input__prefix {
  color: #909399;
}

.el-input__prefix .el-icon {
  font-size: 16px;
}


</style>